﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;

namespace BToolkit
{
    public class MainThreadHelper : MonoBehaviour
    {
        private static MainThreadHelper instance;
        private static Queue<Action> actionsQueue = new Queue<Action>();

        /// <summary>
        /// 在主线程里初始化
        /// </summary>
        public static void Init()
        {
            if (!instance)
            {
                instance = FindObjectOfType<MainThreadHelper>();
                if (!instance)
                {
                    GameObject go = new GameObject("MainThreadHelper");
                    DontDestroyOnLoad(go);
                    instance = go.AddComponent<MainThreadHelper>();
                }
            }
        }

        void Update()
        {
            if (actionsQueue.Count > 0)
            {
                lock (actionsQueue)
                {
                    while (actionsQueue.Count > 0)
                    {
                        Action action = actionsQueue.Dequeue();
                        if (action != null)
                        {
                            try
                            {
                                action();
                            }
                            catch { }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 子线程传入函数，在主线程执行
        /// </summary>
        public static void Run(Action action)
        {
            lock (actionsQueue)
            {
                actionsQueue.Enqueue(action);
            }
        }
    }
}
